package com.jse.jdbc;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.jse.json.Json;

public class Pager implements Serializable {

    private static final long serialVersionUID = 8848523495013555357L;

    private int num=1;
    private int size=10;
    private int pages;
    private long total;
    private int code=0;
    private String sql;
    private List<?> data=new ArrayList<>();
    private String msg;

	public Pager() {
    }

    public Pager(int num) {
        this(num,10);
    }

    public Pager(int num,int size) {
        this(num, size,null);
    }
    public Pager(int num,int size,String sql) {
        if (num < 1)
            num = 1;
        if (size < 1)
            size = 10;
        this.num = num;
        this.size = size;
        this.sql=sql;
    }

    public Pager resetPage() {
        pages = -1;
        return this;
    }

    public void setPages(int page) {
		this.pages = page;
	}
    public int getPages() {
        if (pages < 0)
            pages = (int) Math.ceil((double) total / size);
        return pages;
    }

    public int getNum() {
        return num;
    }
    
    public int getSize() {
        return size;
    }

    public long getTotal() {
        return total;
    }

    public Pager setNum(int pn) {
        num = pn;
        return this;
    }

    public Pager setSize(int size) {
        this.size = (size > 0 ? size : 10);
        return resetPage();
    }

    public Pager setTotal(long total) {
        this.total = total > 0 ? total : 0;
        this.pages = (int) Math.ceil((double) total / size);
        return this;
    }

    public int getOffset() {
        return size * (num - 1);
    }

    public List<?> getData() {
		return data;
	}
//	public void setData(List<?> data) {
//		this.data = data;
//	}
	public void addData(Collection list) {
		this.data.addAll(list);
	}

	@Override
	public String toString() {
		return toJson();
	}
	
	public String limit() {
//		switch (Jdbc.type) {
//		default ->
//		 " limit %d,%d".formatted(getOffset(),this.size);
//		}
		return " limit %d,%d".formatted(getOffset(),this.size);
	}
	
	public String toJson() {
    	return Json.toJson(this);
    }

    public boolean isFirst() {
        return num == 1;
    }

    public boolean isLast() {
        if (pages == 0)
            return true;
        return num == pages;
    }

    public boolean hasNext() {
        return !isLast();
    }

    public boolean hasPrevious() {
        return !isFirst();
    }

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object toSQL() {
		return " limit %d,%d".formatted(getOffset(),this.size);
	}

	
	
}
